//
//  HMPictureView.swift
//  WeiBo
//
//  Created by Feng on 2017/6/10.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit
import SDWebImage

//item之间的间距
private let itemMargin: CGFloat = 5.0
//item的长宽
private let itemWidth: CGFloat = (ScreenWidth - 2 * itemMargin - 2 * HomeCellMargin) / 3

class HMPictureView: UICollectionView {

    //创建layout
    private let pictureViewLayout = UICollectionViewFlowLayout()
    
    //图片数据源
    var picUrls: [HMHomePicInfo]?
    {
        didSet{
            contentLabel.text = "\(picUrls?.count ?? 0)"
            
            guard let picUrlsCount = picUrls?.count else {
                
                return
            }
            
            print("图片个数\(picUrlsCount)")
            
            if picUrlsCount > 0
            {
                calPictureViewSize(count: picUrlsCount)
            }
            
            //数据源发生变化,需要重新加载数据
            reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        pictureViewLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        pictureViewLayout.minimumLineSpacing = itemMargin
        pictureViewLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: pictureViewLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: --懒加载控件
    private lazy var contentLabel: UILabel =
    {
        let label = UILabel(fontSize: 20, textColor: UIColor.orange)
        
        return label
    }()
    
    //MARK: --设置约束
    private func setupUI()
    {
//        backgroundColor = RandomColor()
        
        //设置代理
        dataSource = self
        delegate = self
        //注册
        register(HMHomePictureViewCell.self, forCellWithReuseIdentifier: HomePictureViewIdentifier)
        
        addSubview(contentLabel)
        
        contentLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    
    //MARK: --计算item大小
    private func calPictureViewSize(count: Int)
    {
        //判断图片个数是不是1, 如果是,就进行特殊判断
        if count == 1
        {
            let localImageStr = picUrls!.last!.thumbnail_pic!
            //取出图片
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: localImageStr)
            {
                var localImageSize = localImage.size
                
                print(localImageSize)
                
                //如果尺寸太小或过大,需要进行处理
                if localImageSize.width < 150
                {
                    let newWidth: CGFloat = 150
                    let newHight: CGFloat = newWidth * localImageSize.height / localImageSize.width
                    localImageSize = CGSize(width: newWidth, height: newHight)
                }
                
                if localImageSize.height > 150
                {
                    localImageSize.height = 150
                }
                
                print(localImageSize)
                
                //更新约束
                self.snp.updateConstraints({ (make) in
                    make.size.equalTo(localImageSize).priority(.high)
                })
                
                //修改视图的item的大小
                let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = localImageSize
                
                return
            }
        }
        
        //计算列数
        let column = count > 3 ? 3 : count
        //计算行数
        let row = (count - 1) / 3 + 1
        //计算配图视图宽度
        let pictureViewWidth = itemWidth * CGFloat(column) + itemMargin * CGFloat(column - 1)
        let pictureViewHeight = itemWidth * CGFloat(row) + itemMargin * CGFloat(row - 1)
        let pictureViewSize = CGSize(width: pictureViewWidth, height: pictureViewHeight)
        //更新视图大小
        self.snp.updateConstraints { (make) in
            make.size.equalTo(pictureViewSize).priority(.high)
        }
        //修改视图的item的大小
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
    }
}

//MARK: --collectionView 的数据源方法
extension HMPictureView: UICollectionViewDataSource, UICollectionViewDelegate,SDPhotoBrowserDelegate
{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePictureViewIdentifier, for: indexPath) as! HMHomePictureViewCell
        
        cell.thumbnailPic = picUrls![indexPath.item]
        cell.backgroundColor = RandomColor()
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
        
    }
    //  返回高清的url
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        
        return URL(string: urlStr)
    }
    //  返回占位图片
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! HMHomePictureViewCell
        return cell.thumbnailView.image
    }
}

//MARK: --自定义首页配图cell
class HMHomePictureViewCell: UICollectionViewCell
{
    //要显示的图片
    var thumbnailPic: HMHomePicInfo?
    {
        didSet {
            
            guard let picStr = thumbnailPic?.thumbnail_pic else
            {
                return
            }
            
            let url = URL(string: picStr)
            thumbnailView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big"))
            
            if picStr.hasSuffix(".gif")
            {
                gifImageView.isHidden = false
            }
            else
            {
                gifImageView.isHidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载图片
    fileprivate lazy var thumbnailView: UIImageView =
    {
        let imageView = UIImageView()
        
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        
        return imageView
    }()
    
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    //设置约束
    func setupUI()
    {
        addSubview(thumbnailView)
        addSubview(gifImageView)
        
        thumbnailView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        gifImageView.snp.makeConstraints { (make) in
            make.trailing.bottom.equalTo(self)
        }
    }
}
